package com.secure.orm.thirdPay.tenpay;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.secure.common.util.PayUtil;
import com.secure.orm.enums.PayType;
import com.secure.orm.enums.PaymentOrderType;
import com.secure.orm.enums.ThirdPayNotifyType;
import com.secure.orm.model.PayOrder;
import com.secure.orm.model.response.ViewData;
import com.secure.orm.thirdPay.AbstractThirdPay;

public class Tenpay extends AbstractThirdPay {
	protected Log logger = LogFactory.getLog(Tenpay.class);

	public Tenpay() {
		super();
	}

	// 请求 url
	@Override
	public String pay(PayOrder payOrder) {
		if (null == payOrder || null == payOrder.getOrderId())
			return null;
		Map<String, String> m = new TreeMap<String, String>();
		// 金额
		int totalFee = PayUtil.mulToInt(String.valueOf(payOrder.getOrderAmount()), String.valueOf(100));
        String domain = properties.getProperty("base.domain").trim();
		try {
			// 商户号
			m.put("partner", properties.getProperty("tenpay.partner"));
			// 商家订单号
			m.put("out_trade_no", payOrder.getOrderId());
			// 商品金额,以分为单位
			m.put("total_fee", String.valueOf(totalFee));
			// 交易完成后跳转的URL
			m.put("return_url", domain+properties.getProperty("tenpay.notify_url"));
			// 接收财付通通知的URL
			m.put("notify_url", domain+properties.getProperty("tenpay.return_url"));
			// 商品描述
			m.put("body", payOrder.getSubject());
			// 银行类型
			m.put("bank_type", TenpayConfig.BANK_TYPE);
			// 订单生成的机器IP，指用户浏览器端IP，不是商户服务器IP
			m.put("spbill_create_ip", InetAddress.getLocalHost().getHostAddress());
			// 现金支付币种,取值：1（人民币）,默认值是1，暂只支持1
			m.put("fee_type", "1");
			// 签名类型，取值：MD5、RSA，默认：MD5
			m.put("sign_type", TenpayConfig.signType);
			// 版本号，默认为1.0
			m.put("service_version", TenpayConfig.serviceVersion);
			// 字符编码,取值：GBK、UTF-8，默认：GBK。
			m.put("input_charset", TenpayConfig.inputCharset);
			// 多密钥支持的密钥序号，默认1
			m.put("sign_key_index", "1");
			// 附加数据，原样返回
			m.put("attach", payOrder.getUserId());
			// 商品费用，单位为分 如果有值，必须保证transport_fee + product_fee=total_fee
			m.put("product_fee", String.valueOf(totalFee));
			// 物流费用，单位为分
			m.put("transport_fee", "0");
			// 订单生成时间，格式为yyyyMMddhhmmss
			m.put("time_start", PayUtil.formatTime(null, "yyyyMMddHHmmss"));
			// 订单失效时间，格式为yyyyMMddhhmmss
			m.put("time_expire", "");
			// 买方的财付通账户(QQ 或EMAIL)
			m.put("buyer_id", "");
			// 商品标记，优惠券时可能用到
			m.put("goods_tag", "");
			String sign = mergeSign(m);
			// 签名
			m.put("sign", sign);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return PayUtil.buildForm(properties.getProperty("tenpay.gate_url"), m, "POST");
	}
	
	public String mergeSign(Map<String, String> Params) {
		StringBuffer sb = new StringBuffer();
		for (Entry<String, String> entry : Params.entrySet()) {
			String k = entry.getKey();
			String v = entry.getValue();
			if (!StringUtils.isEmpty(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + properties.getProperty("tenpay.key"));
		return MD5Util.MD5Encode(sb.toString(), "utf-8").toLowerCase();
	}

	@Override
	public Object handleResponse(Map<String, String> requestParamsMap, ThirdPayNotifyType thirdPayNotifyType) {
		ViewData view = verifyThirdPayResponse(requestParamsMap);

		String tradeStatus = requestParamsMap.get(TenpayConfig.trade_status);
		String orderId = requestParamsMap.get(TenpayConfig.out_trade_no);
		Map<String, Object> resultMap = new HashMap<String, Object>();

		if (view.getCode()==-1) {
			resultMap.put(orderId, PayType.Tenpay.name() + "notify verify fail");
		} else {
			if (TenpayConfig.trade_success.equals(tradeStatus)) {
				resultMap.put(orderId, PayType.Tenpay.name() + PaymentOrderType.SCCUESS.name());
			} else {
				if (thirdPayNotifyType.getValue() == ThirdPayNotifyType.RETURN .getValue())
					view.setCode(-1);
				resultMap.put(orderId, PayType.Tenpay.name() + tradeStatus);
			}
		}
		view.setResult(resultMap);
		return view;
	}

//	@Override
//	public Object queryPayInfo(Map<String, String> requestParamsMap) {
//		try {
//			// 创建查询请求对象
//			RequestHandler reqHandler = new RequestHandler(null, null);
//			// 通信对象
//			TenpayHttpClient httpClient = new TenpayHttpClient();
//			// 应答对象
//			ClientResponseHandler resHandler = new ClientResponseHandler();
//
//			// 设置请求参数
//			reqHandler.init();
//			reqHandler.setKey(properties.getProperty("tenpay.key"));
//			reqHandler.setGateUrl(properties.getProperty("tenpay.query_url"));
//
//			// 设置接口参数
//			reqHandler.setParameter("partner", properties.getProperty("tenpay.partner"));
//
//			// out_trade_no和transaction_id至少一个必填，同时存在时transaction_id优先
//			reqHandler.setParameter("out_trade_no",
//					requestParamsMap.get("orderId"));
//
//			// 设置通信参数
//			// 设置请求返回的等待时间
//			httpClient.setTimeOut(5);
//
//			// 设置请求内容
//			String requestUrl = reqHandler.getRequestURL();
//			httpClient.setReqContent(requestUrl);
//			String rescontent = "null";
//
//			// 后台调用
//			if (httpClient.call()) {
//				// 设置结果参数
//				rescontent = httpClient.getResContent();
//				resHandler.setContent(rescontent);
//				resHandler.setKey(properties.getProperty("tenpay.key"));
//
//				// 获取返回参数
//				String retcode = resHandler.getParameter("retcode");
//				String thirdTradeNo = resHandler.getParameter("transaction_id");
//				String price = resHandler.getParameter("total_fee");
//				Map<String, String> map = new HashMap<String, String>();
//				map.put("thirdTradeNo", thirdTradeNo);
//				map.put("price", price);
//
//				if (resHandler.isTenpaySign() && TenpayConfig.trade_success.equals(retcode)) {
//					logger.warn("tp_queryTencentPayOrder_订单查询成功");
//					return new ViewData(0, "success", map);
//				}
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return new ViewData(-1, "fail", null);
//	}

	/**
	 * 校验响应签名
	 * @param requestParamsMap
	 * @return
	 */
	private ViewData verifyThirdPayResponse(Map<String, String> requestParamsMap) {
//		HttpServletRequest request = WebUtil.getRequest();
//		HttpServletResponse response = WebUtil.getResponse();
//		ResponseHandler resHandler = new ResponseHandler(request, response);
//		resHandler.setKey(properties.getProperty("tenpay.key"));
//		if (!resHandler.isTenpaySign()) {
//			return new ViewData(-1, "verify fail", null);
//		}
		String sign = mergeSign(requestParamsMap);
		String signRequest = requestParamsMap.get("sign").toLowerCase();
		if (!signRequest.equals(sign)) {
			return new ViewData(-1, "verify fail", null);
		}
		return new ViewData(0, "verify success", null);
	}
	
}
